var OffsetX,OffsetY;
var tagMode = true;
var tag_count = 0;
var block_area = false;
var currentSelection="";
var currentElement;

var TagInfo=Array();
var currentTag;

var editor_on = false;
var button_Edit;
var button_Delete;
var button_Config;
var editor_config;

$(document).ready(function(){
	event_register();
})	

window.onbeforeunload = function(){
	return "頁籤資訊尚未儲存!";
}

function event_register(){	//set events of components
	$("*").hover(
		function(){//recording current cover element
			currentElement = $(this);
			//$(this).css("border","1px solid red");
		},
		function(){
			//$(this).css("border","0");
		}
	);

	$(document).mousemove(function(e){	//recording current coordinate of curser
		OffsetX = e.pageX;
		OffsetY = e.pageY;
	}); 
	
	$(document).dblclick(function(e){	//adding tag
		if(!block_area && tagMode)
			new_mark(OffsetX,OffsetY);
	});
	
	$(document).mousedown(function(){	//mouse down: remove previous highlight
		$(document).removeHighlight(currentSelection.toString());
	});
	
	$(document).mouseup(function(){	//mouseup: add highlight to selection
		getselecttext();
		if(currentSelection!=''){
			currentElement.highlight(currentSelection.toString());
			//show menu
		}
	});
	
	$(document).keydown(function(e){
		if(e.keyCode==27 && $("#Tags").dialog("isOpen"))	//press ESC to close tag dialog
			$("#Tags").dialog("close");
	})
	
	$('#dialog_link, ul#icons li').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);
	
	$("#toolbar").hover(
		function(){block_area = true},
		function(){block_area = false}
	);
	
	marker_register();
	dialog_register();
}

function marker_register(){
	//let tags bacome translucent while curser over tags
	$(".marker").hover(
		function(){
			block_area = true;
			$(this).addClass("marker_over");
		},
		function(){
			block_area = false;
			$(this).removeClass("marker_over");
		}
	);
	
	$(".marker").click(function(){	//show tag content
		if($("#Tags").dialog("isOpen")){
			if(currentTag.ID==$(this).attr("id")){	//click current tag: do nothing
				//$("#Tags").dialog("close");
				return;
			}
			else{	//other tag
				if($("#Tags").dialog("isOpen")){	//editor opened: save previous tag data
					dialogClose($("#Tags"));
				}
			}
		}
		
		//set current tag info
		currentTag = TagInfo[$(this).attr("id")];
		loadTag();
	});
}

function dialog_register(){
	$("#Tags").dialog({
		//modal: true,	//block page
		width: 500,
		minWidth: 300,
		height: 300,
		minHeight: 200,
		show: "slide",
		hide: "slide",
		autoOpen: false,
		buttons:{
			"Tag_Edit":function(){	//open editor
				if(!editor_on){
					saveTag($(this).dialog("option","position"),[$(this).dialog("option","width"),$(this).dialog("option","height")]);
					$(this).dialog({
						minWidth:600,
						minHeight:360,
						height:($(this).dialog("option","height")<360)?360:$(this).dialog("option","height")
					});
					editor_config = {
						language : "zh", //語系
						toolbar : "Normal", //toolbar模式
						width: "100%",
						height: $(this).dialog("option","height")-200,
						resize_enabled: false,
						removePlugins: 'elementspath',
						enterMode: CKEDITOR.ENTER_BR
					};
					editMode(true);
				}
				else{
					$(this).dialog({
						minWidth:300,
						minHeight:200,
						width:currentTag.size[0],
						height:currentTag.size[1]
					});
					editMode(false);
				}
			},
			"Tag_Delete":function(){	//delete tag
				$("#"+currentTag.ID).remove();
				$("#"+currentTag.ID+"_content").remove();
				delete TagInfo[currentTag.ID];
				$(this).dialog("close");
			},
			"Tag_Config":function(){	//tag configuration
				alert("config");
			}
		},
		resizeStop: function(event, ui) {
			if(editor_on){
				var editor = $("#tag_content").ckeditorGet();
				editor.resize("100%", $(this).dialog("option","height")-110);
			}
		},
		open: function(){	//when open tag content, adding tag is not allowed.
			tagMode = false;
		},
		close: function(){
			dialogClose($(this));
		}
	});
	
	//replace text on buttons by icons
	button_Edit = $("span:contains(Tag_Edit)");
	button_Delete = $("span:contains(Tag_Delete)");
	button_Config = $("span:contains(Tag_Config)");
	button_Edit.html('<span class="ui-icon ui-icon-pencil"></span>');
	button_Delete.html('<span class="ui-icon ui-icon-trash"></span>');
	button_Config.html('<span class="ui-icon ui-icon-Gear"></span>');
	
	$('ul#icons li').hover(
		function() { $(this).addClass('ui-state-hover'); }, 
		function() { $(this).removeClass('ui-state-hover'); }
	);
}

function dialogClose(d){
	if(editor_on)
		editMode(false);
	saveTag(d.dialog("option","position"),[d.dialog("option","width"),d.dialog("option","height")]);
	tagMode = true;
}

function editMode(state){
	if(state){	//on
		$("#tag_content").ckeditor(editor_config);
		editor_on = true;
		button_Edit.html('<span class="ui-icon ui-icon-closethick"></span>');
	}
	else{	//off
		$("#tag_content").ckeditorGet().destroy();
		editor_on = false;
		button_Edit.html('<span class="ui-icon ui-icon-pencil"></span>');
	}
}

function loadTag(){
	if(currentTag.newTag){
		currentTag.pos = [currentTag.pos[0]+30,currentTag.pos[1]+30];
		currentTag.newTag = false;
	}
	//show content
	var time = currentTag.time.year+"/"+currentTag.time.month+"/"+currentTag.time.day+" "+
		currentTag.time.hour+":"+currentTag.time.minute+":"+currentTag.time.second;
	$("#tag_content").html(currentTag.content);
	$("#Tags").dialog("option","position",currentTag.pos);
	$("#Tags").dialog("option","width",currentTag.size[0]);
	$("#Tags").dialog("option","height",currentTag.size[1]);
	$("#Tags").dialog("option","title",currentTag.tagger+"("+time+")");
	$("#Tags").dialog("open");
}

function saveTag(pos,size){	//saving tag info
	currentTag.content=$("#tag_content").html();
	currentTag.pos = pos;
	currentTag.size = size;
}

function new_mark(x,y){ //create new tag on page
	var new_markerID = 'tag'+tag_count;
	var pos = [x-15,y-15];
	var size = [500,300];
	var time = new getToday();
	var test;
	TagInfo[new_markerID] = {
		"newTag":true,
		"ID":new_markerID,
		"pos":pos,
		"size":size,
		"content":"",
		"tagger":"Link",
		"time":time
	};
	$("body").append('<img src="images/Marker1.png" id="'+new_markerID+'" class="marker" '+
		'style="position:absolute;left:'+TagInfo[new_markerID].pos[0]+'px;top:'+TagInfo[new_markerID].pos[1]+'px;width:30px">'+
		'<div id="'+new_markerID+'_content" style="display:none"></div>');
	tag_count++;
	marker_register();
}

function getselecttext(){	//get selecting text
	var t='';
	if(window.getSelection){t=window.getSelection();}
	else if(document.getSelection){t=document.getSelection();}
	else if(window.document.selection){t=window.document.selection.createRange().text;}
	currentSelection = t;
}

function show(){
	$("#Tags").dialog("open");
}
function hide(){
	alert(currentTag.content);
}

function getToday() {
	//得到今天的年,月,日
	this.now = new Date();
	this.year = this.now.getFullYear();
	this.month = this.now.getMonth();
	this.day = this.now.getDate();
	this.hour = this.now.getHours();
	this.minute = this.now.getMinutes();
	this.second = this.now.getSeconds();
}